@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
    ViewData["Title"] = "库存盘点编辑";
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>库存盘点编辑</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="layui-card">
        <div class="layui-card-header">
            <div class="layui-row">
                <div class="layui-col-md6">
                    <h2 id="pageTitle">库存盘点编辑</h2>
                </div>
                <div class="layui-col-md6" style="text-align: right;">
                    <button class="layui-btn" id="btnSave">
                        <i class="layui-icon">&#xe605;</i> 保存
                    </button>
                    <button class="layui-btn layui-btn-primary" id="btnCancel">
                        <i class="layui-icon">&#xe669;</i> 取消
                    </button>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <!-- 编辑表单 -->
            <form class="layui-form" lay-filter="addEditForm" style="padding:20px 30px 0 0;">
                <input type="hidden" name="id" />
                <div class="layui-form-item">
                    <label class="layui-form-label">盘点单编号</label>
                    <div class="layui-input-block">
                        <input type="text" name="countingOrderCode" required lay-verify="required" placeholder="请输入盘点单编号" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">盘点单名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="countingOrderName" required lay-verify="required" placeholder="请输入盘点单名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">盘点类型</label>
                    <div class="layui-input-block">
                        <input type="text" name="countingType" required lay-verify="required" placeholder="请输入盘点类型" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">盘点日期</label>
                    <div class="layui-input-block">
                        <input type="text" name="countingDate" required lay-verify="required" placeholder="请选择盘点日期" class="layui-input" id="countingDateInput">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">盘点人</label>
                    <div class="layui-input-block">
                        <input type="text" name="countingPerson" required lay-verify="required" placeholder="请输入盘点人" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">仓库名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="repositoryName" required lay-verify="required" placeholder="请输入仓库名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">单据状态</label>
                    <div class="layui-input-block">
                        <select name="state" lay-verify="required">
                            <option value="">请选择状态</option>
                            <option value="0">草稿</option>
                            <option value="1">已完成</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script>
        layui.use(['form', 'layer', 'laydate'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var $ = layui.$;

            // 获取URL参数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]); return null;
            }

            // 初始化页面
            function initPage() {
                var id = getUrlParam('id');
                var isEdit = id && id !== 'undefined';
                
                // 设置页面标题
                $('#pageTitle').text(isEdit ? '编辑盘点单' : '新增盘点单');
                
                // 初始化日期选择器
                laydate.render({
                    elem: '#countingDateInput',
                    type: 'datetime'
                });

                if (isEdit) {
                    // 编辑模式：加载数据
                    loadData(id);
                } else {
                    // 新增模式：生成随机编号
                    var randomCode = generateRandomCode();
                    $("input[name='countingOrderCode']").val(randomCode);
                }
            }

            // 加载数据
            function loadData(id) {
                $.ajax({
                    url: '/InventoryCounts/GetInventoryCounts',
                    type: 'GET',
                    data: { id: id },
                    success: function(res) {
                        if (res && res.countingDate) {
                            var date = new Date(res.countingDate);
                            res.countingDate = layui.util.toDateString(date, 'yyyy-MM-dd HH:mm:ss');
                        }
                        form.val('addEditForm', {
                            'id': res.id,
                            'countingOrderCode': res.countingOrderCode,
                            'countingOrderName': res.countingOrderName,
                            'countingType': res.countingType,
                            'countingDate': res.countingDate,
                            'countingPerson': res.countingPerson,
                            'repositoryName': res.repositoryName,
                            'state': res.state
                        });
                    },
                    error: function(xhr) {
                        var errorMsg = '';
                        try {
                            var error = JSON.parse(xhr.responseText);
                            errorMsg = error.message || error.error.message || '获取数据失败';
                        } catch(e) {
                            errorMsg = xhr.responseText || '获取数据失败';
                        }
                        layer.msg(errorMsg, {icon: 2});
                    }
                });
            }

            // 随机编号生成函数
            function generateRandomCode() {
                var now = new Date();
                var yyyy = now.getFullYear();
                var MM = (now.getMonth()+1).toString().padStart(2,'0');
                var dd = now.getDate().toString().padStart(2,'0');
                var hh = now.getHours().toString().padStart(2,'0');
                var mm = now.getMinutes().toString().padStart(2,'0');
                var ss = now.getSeconds().toString().padStart(2,'0');
                var rand = Math.floor(1000 + Math.random() * 9000);
                return 'PD' + yyyy + MM + dd + hh + mm + ss + rand;
            }

            // 保存按钮点击事件
            $('#btnSave').on('click', function() {
                var formData = form.val('addEditForm');
                
                // 表单验证
                if(!formData.countingOrderCode) {
                    layer.msg('请输入盘点单编号');
                    return;
                }
                if(!formData.countingOrderName) {
                    layer.msg('请输入盘点单名称');
                    return;
                }
                if(!formData.countingType) {
                    layer.msg('请输入盘点类型');
                    return;
                }
                if(!formData.countingDate) {
                    layer.msg('请选择盘点日期');
                    return;
                }
                if(!formData.countingPerson) {
                    layer.msg('请输入盘点人');
                    return;
                }
                if(!formData.repositoryName) {
                    layer.msg('请输入仓库名称');
                    return;
                }
                if(!formData.state) {
                    layer.msg('请选择单据状态');
                    return;
                }

                var url = formData.id ? '/InventoryCounts/UpdateInventoryCounts' : '/InventoryCounts/AddInventoryCounts';
                var type = formData.id ? 'PUT' : 'POST';

                // 处理日期格式
                if(formData.countingDate && formData.countingDate.indexOf('T') > 0){
                    formData.countingDate = formData.countingDate.replace('T', ' ');
                }

                // 转换state为数字
                formData.state = parseInt(formData.state);

                // 构建提交数据
                var submitData = {
                    countingOrderCode: formData.countingOrderCode,
                    countingOrderName: formData.countingOrderName,
                    countingType: formData.countingType,
                    countingDate: formData.countingDate,
                    countingPerson: formData.countingPerson,
                    repositoryName: formData.repositoryName,
                    state: formData.state
                };

                // 如果是编辑模式，添加id
                if(formData.id) {
                    submitData.id = parseInt(formData.id);
                }

                console.log('提交的数据：', submitData); // 用于调试

                $.ajax({
                    url: url,
                    type: type,
                    data: JSON.stringify(submitData),
                    contentType: 'application/json',
                    success: function(res){
                        if(res && res.error) {
                            layer.msg(res.error.message || '保存失败', {icon: 2});
                            return;
                        }
                        layer.msg('保存成功', {icon: 1}, function(){
                            // 返回列表页面
                            window.location.href = '/InventoryCounts/Index';
                        });
                    },
                    error: function(xhr){
                        var errorMsg = '';
                        try {
                            var error = JSON.parse(xhr.responseText);
                            errorMsg = error.message || error.error.message || '保存失败';
                        } catch(e) {
                            errorMsg = xhr.responseText || '保存失败';
                        }
                        layer.msg(errorMsg, {icon: 2});
                        console.log('错误详情：', xhr.responseText); // 用于调试
                    }
                });
            });

            // 取消按钮点击事件
            $('#btnCancel').on('click', function() {
                window.location.href = '/InventoryCounts/Index';
            });

            // 初始化页面
            initPage();
        });
    </script>
</body>
</html> 